package com.shuai.frame.bootstrap;

import com.shuai.frame.config.XSRpcApplicationContext;
import com.shuai.frame.config.XSRpcConfig;
import com.shuai.frame.config.XsRPCRegistryCenterConfig;
import com.shuai.frame.constant.RpcConstant;
import com.shuai.frame.factory.RegistryFactory;
import com.shuai.frame.model.ServiceMetaInfo;
import com.shuai.frame.registry.LocalRegister;
import com.shuai.frame.registry.RegistryCenter;
import com.shuai.frame.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * @author bxs
 * @version 1.0
 * @Date 2024/7/30
 */
public class ProviderBootstrap {
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        // RPC 框架初始化（配置和注册中心）
        XSRpcApplicationContext.init();
        // 全局配置
        XSRpcConfig rpcConfig = XSRpcApplicationContext.getXSRpConfig();
        XsRPCRegistryCenterConfig registryConfig = rpcConfig.getRegistryCenterConfig();
        RegistryCenter registryCenter = RegistryFactory.getRegistryCenter(registryConfig.getRegistryType());

        // 注册服务
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            ServiceMetaInfo serviceMetaInfo = ServiceMetaInfo.builder()
                    .serviceName(serviceRegisterInfo.getServiceName())
                    .serviceHost(rpcConfig.getServerAddress())
                    .servicePort(rpcConfig.getServerPort())
                    .serviceVersion(RpcConstant.DEFAULT_SERVICE_VERSION)
                    .serviceDesc(serviceRegisterInfo.getDesc())
                    .build();
            String serviceName = serviceMetaInfo.getServiceName();
            // 本地注册
            LocalRegister.register(serviceName, serviceRegisterInfo.getImplClass());
            try {
                registryCenter.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + " 服务注册失败", e);
            }
        }

        // 启动服务器
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.start(rpcConfig.getServerPort());
    }
}
